package com.kpy.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @auther: kpy
 * @version: 1.0
 * @Package: com.kpy.utils
 * @data: 2021/12/14 22:59
 * @discription: 生成MD工具类
 **/
public class MD5Tools {
    /**
     * 生成MD5
     **/
    public static String genMD5(String data) {
        if (data == null || data == "") {
            return null;
        }
        MessageDigest md = null;
        StringBuffer MD5 = new StringBuffer();
        try {
            md = MessageDigest.getInstance("MD5");
            byte[] array =  md.digest(data.getBytes(StandardCharsets.UTF_8));
            for(byte item : array){
                MD5.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1,3));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return MD5.toString().toUpperCase();
    }

    /**
     * 生成MD5
     **/
    public static String genMD5_1(String data) {
        if (data == null || data == "") {
            return null;
        }
        String MD5 = DigestUtils.md5Hex(data.getBytes(StandardCharsets.UTF_8));
        return MD5.toUpperCase();
    }

    public static String genMD5_2(String data) {
        if (data == null || data == "") {
            return null;
        }
        String MD5 = org.springframework.util.DigestUtils.md5DigestAsHex(data.getBytes(StandardCharsets.UTF_8));
        return MD5.toUpperCase();
    }
}
